<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['app_dir'] . '/includes/object.class.php');
    require_once($config['app_dir'] . '/includes/db.class.php');
    require_once($config['app_dir'] . '/includes/FormParams.class.php');
    require_once($config['app_dir'] . '/includes/template.class.php');
    require_once($config['app_dir'] . '/includes/params.class.php');
    require_once($config['app_dir'] . '/includes/mailer.class.php');

    require_once($config['app_dir'] . '/classes/user.data.php');
    //require_once($config['app_dir'] . '/classes/StockUserMailer.inc.php');
    require_once($config['app_dir'] . '/classes/StockMailers.class.php');
    require_once($config['app_dir'] . '/classes/translation.class.php');
    require_once($config['app_dir'] . '/classes/class.timezone.php');
    require_once($config['app_dir'] . '/classes/class.mailshots.php');
    //---------------------------------------------------------------------------------------------------
    abstract class objUserAction extends objObject implements iErrorHandler{
            protected $_DataBase = false;
            protected $_Params  = false;

            protected $_querys = array();
            //public  $TranslationMessage = false;

        public function __construct() {
            $this->_DataBase = objDataBase::GetInstance();
            $this->_sqls();
            //$TranslationMessage = objTranslationMessage::GetInstance();
            //$TranslationMessage->SetLang($TranslationMessage->GetLang());
			//$this->TranslationMessage= $TranslationMessage;
        } //constructor

        protected function _Perform() {
            $this->_Params = new objFormParams('post');
        } //_Perform

        public function Render() {
            if( !$this->_Perform() ) return false;
            return true;
        } //Render

        public function Display() {
            echo $this->Render();
        } //Display

        public function ClassName() {
            return  __CLASS__;
        }//ClassName
    } //class UserAction


    //---------------------------------------------------------------------------------------------------
    class objUserActivationBody {
            public $public_root ='';
            public $id = false;
            public $login = false;
            public $name = false;

        public function Fetch() {
            $Body = new objTemplate();
            $Body->Assign('url', $this->public_root . 'index.php');
            $Body->Assign('code', md5(strval($this->id).$this->login));
            $Body->Assign('name', $this->name);
            return $Body->Fetch('EmailConfirm.tpl');
        } //Fetch

    } //class UserActivationBody
    //---------------------------------------------------------------------------------------------------
    class objReActivationModel {
            public $email=false;
            protected $UserRecord = false;

        public function __construct($aEmail=false) {
            $this->email = $aEmail;

            $UserModel = new objUserModel();
            $this->UserRecord = $UserModel->ActiveRecord();
        } //constructor

        public function isEmpty() {
            return empty($this->email) || false===$this->email;
        }//isEmpty

        protected function Perform() {
            if( $this->isEmpty() ) return false;

            $this->UserRecord->Load("Login=\"$this->email\"");
            return true;
        } //Perform

        public function Fetch() {
            if( !$this->Perform() ) return false;
            $ActivationBody = new objUserActivationBody();
            $ActivationBody->id = $this->UserRecord->userid;
            $ActivationBody->login = $this->UserRecord->login;
            $ActivationBody->name = $this->UserRecord->name;
            return $ActivationBody->Fetch();
        } //Fetch
    }//class ReActivationModel

    //---------------------------------------------------------------------------------------------------
    class objUserSignUp extends objUserAction{
            public $public_root ='';
            protected $_id = false;
            protected $_data = false;

            protected $_error_str = array('no errors',
                                          'Account already exists',
                                          'Database error',
                                          'Mailer error ');
        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        protected function _Perform() {
          global $Staff;
            parent::_Perform();

            if( !$this->_Params->isEmpty() ) {
                $params = $this->_Params->getAssocArray();
                try {
                    //add check for existing users
                    $user = $this->_DataBase->handler->GetRow($this->_querys['find_user'], array($params['login']));

                    if( $user["count_user"]>0 ) {
                        $this->_error_no = 1;
                        return true;
                    } else {
                       	// simple protection from direct POSTing
                    	if ( count(explode("@", $params['login'])) < 2 || count(explode(".", $params['login'])) < 2 )
                    		exit("Don't even think about it!");
                        //insert new user
                        if( !($lang = $Staff->Session->Get('lang')) ) $lang='en';
						if( !($gad = $Staff->Session->Get('gad')) ) $gad='';
                        $this->_DataBase->handler->Execute($this->_querys['insert_user'], array($params['login'], $params['pass'], $params['name'], $lang, $gad, 29)); // $params['timezone']
                        $this->_id = $this->_DataBase->handler->Insert_ID();


                        //track user IP, host etc/
                    	$objTtracker = new objUserTracking();
                    	$objTtracker->getTrackingInfo($this->_id);
                   		$objTtracker->insertTrackingInfo($this->_id);


                    }
                } catch(exception $e) {
                    if (true == $this->_DataBase->handler->debug ) {
                        adodb_pr($e);
                        $e = adodb_backtrace($e->trace);
                    }
                    print('Error: '.$e->sql.' '.$e->getMessage());
                    return false;
                }
            }
            return true;
        } //_Perform

        protected function _Mailer() {
            $ActivationBody = new objUserActivationBody();
            $ActivationBody->public_root = $this->public_root;
            $ActivationBody->id = strval($this->_id);
            $ActivationBody->login = $this->_Params['login'];
            $ActivationBody->name = $this->_Params['name'];
            //-------------------------------------------------------------------------------------------
            $Mailer = new objMailer();
            $Mailer->Subject = $this->TranslationMessage->GetMessage('mail_subject__email_activate');
            $Mailer->From = 'support@intelli4x.com';
            $Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service');
            $Mailer->isHTML(true);
            $Mailer->Body = $ActivationBody->Fetch();//$BodyTemplate->Fetch('EmailConfirm.tpl');!!!!2007 09 07
            $Mailer->AddAddress($this->_Params['login']);
            if( !$Mailer->Send() ) {
                $this->_error_no = 3;
                $this->_error_str[$this->_error_no] .= $Mailer->ErrorInfo;
            }
            //-------------------------------------------------------------------------------------------
            $Mailer = new objMailer();
            $Mailer->Subject='New Account: ' . $this->_Params['name'] . ' | ' . $this->_Params['login'];
            $Mailer->From='noreply@intelli4x.com';
            $Mailer->FromName = 'IntelliForex Subscribers';
            $Mailer->AddAddress('stats@intelli4x.com');
            if( !$Mailer->Send() ) {
                $this->_error_no = 3;
                $this->_error_str[$this->_error_no] .= $Mailer->ErrorInfo;
            }
            return ( 3 != $this->_error_no );
        } //_Mail

        protected function _mailAferSignUp() {
            $BodyTemplate = new objTemplate();
            $BodyTemplate->Assign('userName', $this->_Params['name']);
            //-------------------------------------------------------------------------------------------
            $Mailer = new objMailer();
            $Mailer->Subject = $this->TranslationMessage->GetMessage('mail_subject__email_subscractivate');
            $Mailer->From = 'support@intelli4x.com';
            $Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service');
            $Mailer->isHTML(true);
            $Mailer->Body = $BodyTemplate->Fetch('EmailSignUp.tpl');
            $Mailer->AddAddress($this->_Params['login']);
            if( !$Mailer->Send() ) {
                $this->_error_no = 3;
                $this->_error_str[$this->_error_no] .= $Mailer->ErrorInfo;
            }
            //-------------------------------------------------------------------------------------------
            return ( 3 != $this->_error_no );
        } //_mailAferSignUp


        public function Render() {
            if( !parent::Render() ) return false;

            $content = '';
            $params = $this->_Params->GetAssocArray();
            //var_dump($params);
            if( 1==$this->_error_no ) {
                $BodyContent = new objTemplate();
                $content .= $BodyContent->Fetch('users/_sign_up.tpl');
            } elseif( !$this->_Params->isEmpty() ) {
                if( $this->_id ) {
                    $this->_Mailer();
                    //-------------------------------------------------------------------------------------------
                    $AfterContent = new objTemplate();
                    $AfterContent->Assign('data', $params);
                    $content .= $AfterContent->Fetch('users/_after_SignUp.tpl');
                }
            } else {
            	// get all timezones array to draw timezones selectbox
            	$tz = new objTimezone();
            	$timezones = $tz->TZDisplayArr();

                $Form = new objTemplate();
                $Form->Assign('data', $params);
                $Form->Assign('timezones', $timezones);
                $content .= $Form->Fetch('_form_register.tpl');
                unset($timezones);
            }
            return $content;
        }//Render

        protected function _sqls() {
            $this->_querys['find_user'] = 'select count(*) as count_user from fa_users where upper(Login)=upper(?) ';

            $this->_querys['insert_user'] = 'insert into fa_users(Login, Password, Name, Language, gad, Timezone) values(?,?,?,?,?,?)';
        } //_sqls

    } //class UserSignUp

    //---------------------------------------------------------------------------------------------------
    class objUserConfirm  extends objUserAction{
            protected $_Staff = false;
            protected $_data = false;

            protected $_error_str = array('no errors',
                                          'This account is activated already',
                                          'Database error');

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public  function __construct($aStaff) {
            parent::__construct();
            $this->_Staff = $aStaff;
        } //constructor

        protected function _Perform() {
            $this->_Params = new objFormParams('get', '');

            if( !$this->_Params->isEmpty() ) {
                try {
                    //-----------------------------------------------------------------------------------
                    $this->_data = $this->_DataBase->handler->GetRow($this->_querys['find_user'], array($this->_Params['code']));
                    if( empty($this->_data) ) {
                        $this->_error_no = 1;
                        return true;
                    }
                    $this->_DataBase->handler->Execute($this->_querys['update_user'], array($this->_data['UserID']));

                    $this->_DataBase->handler->Execute($this->_querys['trades_user'], array($this->_data['UserID']));
                    $this->_DataBase->handler->Execute($this->_querys['trades_user_ea'], array($this->_data['UserID']));


                    //-----------------------------------------------------------------------------------

                    $this->_Staff->AutoLogin($this->_data['UserID']);
                    $this->_mailAferActivation(); // 'water' email

                    $StockMailer = new objStockUserMailer($this->_data['UserID']);//SendStockGraphUser($this->_data['UserID']);!!!!!!!
                    $StockMailer->Send(); //!!!!!!!!!!!!!!!!
                    //-----------------------------------------------------------------------------------
                } catch(exception $e) {
                    if (true == $this->_DataBase->handler->debug ) {
                        adodb_pr($e);
                        $e = adodb_backtrace($e->trace);
                    }
                    print('Error: '.$e->sql.' '.$e->getMessage());
                    $this->_error_no = 2;
                    return false;
                }
            } // params are not empty - code set
            return true;
        } //perform

        protected function _mailAferActivation() {
            $BodyTemplate = new objTemplate();
            $BodyTemplate->Assign('userName', $this->_data['Name']);
            //-------------------------------------------------------------------------------------------
            $Mailer = new objMailer();
            $Mailer->Subject = $this->TranslationMessage->GetMessage('mail_subject__email_subscractivate');
            $Mailer->From = 'support@intelli4x.com';
            $Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service');
            $Mailer->isHTML(true);
            $Mailer->Body = $BodyTemplate->Fetch('EmailAfterActivation.tpl');
            $Mailer->AddAddress($this->_data['Login']);
            if( !$Mailer->Send() ) {
                $this->_error_no = 3;
                $this->_error_str[$this->_error_no] .= $Mailer->ErrorInfo;
            }
            return ( 3 != $this->_error_no );
        } //_mailAferActivation


        public function Render() {
            if( !$this->_Perform() ) return false;
          global /*$xajax,*/ $config;

            $content = '';
            if( 1==$this->_error_no) {
                	$content .= "<div class='error'>This account is activated already.</div>";
            } elseif( !$this->_error_no ) {
                if( !$this->_Params->isEmpty() ) {
                    //-----------------------------------------------------------------------------------
                    $AfterContent = new objTemplate();
                    $AfterContent->Assign('data', $this->_data);
                    $content .= $AfterContent->Fetch('users/_after_Activation.tpl');
                    //-----------------------------------------------------------------------------------
                    //$SystemSelector = new objSystemSelector(/*false, false*/);
                    //$content .= $SystemSelector->Render();
                    //-----------------------------------------------------------------------------------
                    $Forecasts = new objTemplate();
                    $Forecasts->Assign_by_ref('Staff', $this->_Staff);
/*                    $Forecasts->Assign('xjavascript', $xajax->printJavascript(addslashes($config['xajax']['js'])));    */
                    $content .= $Forecasts->Fetch('texts/_sec_forecasts.tpl');
                    //-----------------------------------------------------------------------------------
                } else {
                    $Form = new objTemplate();
                    $content .= $Form->Fetch('_form_confirm.tpl');
                }
            }
            return $content;
        } //render

        protected function _sqls() {
            $this->_querys['find_user'] = 'select * from fa_users u where md5(concat(cast(u.`UserID` as char), cast(u.Login as char)))=? and Active=0';

            $this->_querys['update_user'] = 'update fa_users set Active=1 where UserID=?';

            $this->_querys['trades_user'] = ' INSERT INTO fa_users_trades(UserID, SystemID, TradeID)   '.
                                            ' (SELECT ? as UserID, ts.SystemID, ts.TradeID ' .
                                            '  FROM fa_trades_systems ts LEFT JOIN fa_systems sa ON sa.SystemID=ts.SystemID ' .
                                            'WHERE sa.Active=1 & ts.Default=1)';
            $this->_querys['trades_user_ea'] = ' INSERT INTO fa_users_trades_ea(UserID, SystemID, TradeID)   '.
                                            ' (SELECT ? as UserID, ts.SystemID, ts.TradeID ' .
                                            '  FROM fa_trades_systems ts LEFT JOIN fa_systems sa ON sa.SystemID=ts.SystemID WHERE sa.Active=1)';
        } //_sqls
    } //class UserConfirm

    //---------------------------------------------------------------------------------------------------
    class objUserProfile extends objUserAction{
            public $id = false;
            private $trades = false;
            private $eatrades = false; // expert Advisor
            public $systems = false;
            public $Staff = false;

        public function ClassName() {
            return  __CLASS__;
        }//ClassName
		
		protected function _mailMMRecommendations($user, $postData) {
			$aData = explode("_", $postData);
			$aAmount = $aData[0];
			$aBroker = $aData[1];
			$aEmail = $aData[2];
		
            $Mailer = new objMailer();
            $Mailer->Subject = "Money Management Recommendations Request";
            $Mailer->From = 'support@intelli4x.com';
            $Mailer->FromName = "IntelliForex Site";
            $Mailer->isHTML(true);
            $Mailer->Body = "Account size: $aAmount<br>Broker: $aBroker<br>E-mail: $aEmail";
            $Mailer->AddAddress('alexander.ganchuk@gmail.com', 'support@intelli4x.com');
			//$Mailer->AddAddress('support@intelli4x.com');
            if( !$Mailer->Send() ) {
                $this->_error_no = 3;
                $this->_error_str[$this->_error_no] .= $Mailer->ErrorInfo;
            }
            //-------------------------------------------------------------------------------------------
            return ( 3 != $this->_error_no );
        } //_mailMMRecommendations

        protected function _Perform() {
            parent::_Perform();

			//if test sms were sent
            if( $_POST['test_sms'] ) {
            	$smsTest = new objMailshot();
   				$smsTest->testSMSEmail($_POST['test_sms']);
         	}
			
			// if money management recommendations requested
			if( $_POST['data_mmRecommend'] ) {
            	$this->_mailMMRecommendations($this->id, $_POST['data_mmRecommend']);
         	}

            if( !$this->_Params->isEmpty() ) {
                $params = $this->_Params->getAssocArray();
                try {
                                        //-----------------------------------------------------------------------------------
                    //update user record in db depending on what form were submitted

                    if( $params['password'] ) $this->UserRecord->password = $params['password'];
                    else {
                    	$this->_DataBase->handler->Execute($this->_querys['delete_trades'], array($this->id));
                    	foreach($params['trades'] as $trade) {
	                        $this->_DataBase->handler->Execute($this->_querys['insert_trades'], explode('_', $trade));
	                    }

                        //process money management settings
                        if ($params['account'] || $params['broker']!=0) {
                        	$rsm = $this->_DataBase->handler->Execute($this->_querys['check_money_record'], array($this->id));
                        	if ($rsm->fields['mm']==0) $this->_DataBase->handler->Execute($this->_querys['insert_money_record'], array($this->id,$params['account'],$params['broker'],$params['cbroker']));
                        	else $this->_DataBase->handler->Execute($this->_querys['update_money_record'], array($params['account'],$params['broker'],$params['cbroker'],$this->id));
                        }

                        //process expert advisor settings
                     	$rs = $this->_DataBase->handler->Execute($this->_querys['check_trades_ea'], array($this->id));
                     	if ($rs->fields['Eatrades']==0) $this->_DataBase->handler->Execute($this->_querys['insert_trades_ea'], array($this->id));
                     	else $this->_DataBase->handler->Execute($this->_querys['deactivate_trades_ea'], array($this->id));

                    	foreach($params['eatrades'] as $eatrade) {
							
                    		$eadata = explode('_', $eatrade);
                    		$eaTrade = $eadata[2];
                    		$eaSystem = $eadata[1];
                    		$eaLot = $params[$eatrade]*1000;
							
							$rsCheck = $this->_DataBase->handler->Execute($this->_querys['check_trade_ea'], array($this->id,$eaSystem,$eaTrade));
							//if no such trade record - insert one/ Useful when adding new systems
							if ($rsCheck->fields['Eatrade']==0) 
								$this->_DataBase->handler->Execute($this->_querys['insert_trade_ea'], array($this->id,$eaSystem,$eaTrade));
	                        $this->_DataBase->handler->Execute($this->_querys['activate_trades_ea'], array($eaLot, $this->id, $eaTrade, $eaSystem));
	                    }

	                    unset($params['trades']);
	                    unset($params['eatrades']);

			            $this->UserRecord->name = $params['name'];
	                    //$this->UserRecord->language = $params['language'];
			            $this->UserRecord->smsaddress = $params['phonemail'];
			            $this->UserRecord->phonecode = $params['pcode'];
			            $this->UserRecord->phonenumber = $params['pnumber'];
			            $this->UserRecord->timezone = $params['timezone'];
			            if( 0!=$params['messagetype'] && 0!=$params['messagetype'] ) $this->UserRecord->messagetype = $params['messagetype'];
		            }

					if( !$params['test_sms'] ) $this->UserRecord->Save();
                    //-----------------------------------------------------------------------------------
                    //$this->_DataBase->handler->Replace('fa_users', $params,  array('userid'), true);
                } catch(exception $e) {
                    if (true == $this->_DataBase->handler->debug ) {
                        adodb_pr($e);
                        $e = adodb_backtrace($e->trace);
                    }
                    print('Error: '.$e->sql.' '.$e->getMessage());
                    return false;
                }
            }
            return true;
        } //Perform

        public function Render() {
            $this->getUserData();
            // get all timezones array to draw timezones selectbox
            $tz = new objTimezone();
            $timezones = $tz->TZDisplayArr();

            $Form = new objTemplate();
            $Form->Assign('data', $this->UserRecord);
            $Form->Assign('timezones', $timezones);
            $Form->Assign('userTimezone', $this->Staff->getUserTimezone());
            $Form->Assign('trades', $this->trades);
            $Form->Assign('eatrades', $this->eatrades);
            //$Form->Assign('ealots', array(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1));
            $Form->Assign('eadefLot', 10);
            $Form->Assign('languages', $this->languages);
            $Form->Assign('money', $this->money);
            $Form->Assign('systems', $this->systems);
            $Form->Assign('brokers', $this->brokers);
            $Form->Assign('menu_sub', $this->sub_menu);echo "\n";
            $Form->Assign('test', $this->test);

            $Form->Assign_by_ref('Staff', $this->Staff);

            return $Form->Fetch('_form_profile.tpl');
        } //Render

        public function getUserData() {
        	//load user data
        	$UserModel = new objUserModel();
            $this->UserRecord = $UserModel->ActiveRecord();
            $this->UserRecord->Load('UserID='.$this->id);

            $this->_sqls();

			//check if there any POST params submitted
            if( !$this->_Perform() ) return false;

            $ParamsTrades = new objParamList('trades');
            //$ParamsTrades->build($this->_DataBase->handler, $this->_querys['select_trades'], 'value', 'name', 'flag', 'group', 'subscribed');

			$ParamsTrades = $this->_DataBase->handler->getAll($this->_querys['select_trades']);

			$this->money = $this->_DataBase->handler->getRow($this->_querys['select_money'],array($this->id));
            $this->brokers = $this->_DataBase->handler->getAll($this->_querys['select_brokers']);


            $ParamEATrades = $this->_DataBase->handler->getAll($this->_querys['select_trades_ea']);

            $this->trades = $ParamsTrades;
            //$this->trades = $ParamsTrades->getAssocArray();
            //$this->eatrades = $ParamEATrades->getAssocArray();
            $this->eatrades = $ParamEATrades;

            //var_dump($this->eatrades);

            $ParamsLang = new objParamList('lang');
            $ParamsLang->build($this->_DataBase->handler, $this->_querys['select_lang']);
            $this->languages = $ParamsLang->getAssocArray();

            $listSystems = new objSystems();
            $this->systems = $listSystems->GetAssocArrByID();
            return true;

        } //getUserData


        protected function _sqls() {

            $this->_querys['select_trades'] =
              " SELECT ".
                " CONCAT('" . $this->UserRecord->userid . "', '_', ts.SystemID, '_', t.TradeID) as value, ".
                " t.Pair as name, ".
                " ts.SystemID as `group`, ".
                " COALESCE( ".
  				              " ( ".
  				               " SELECT ut.TradeID is not null ".
                               " FROM fa_users_trades ut ".
                               " WHERE ut.TradeID = t.TradeID AND ut.SystemID=ts.SystemID AND ut.UserID = ".$this->UserRecord->userid." ".
				              " ), ".
			              " 0) as flag, ".
			     " (SELECT count(*) FROM fa_subscriptions WHERE user_id=".$this->UserRecord->userid." AND subscr_active=1)>0 as subscribed, ".
			     " (SELECT count(*) FROM fa_subscriptions sss WHERE sss.user_id=".$this->UserRecord->userid." AND sss.subscr_active=1 AND sss.subscr_system=ts.SystemID)>0 as subscr_system ".
              " FROM ".
  	              " fa_trades t ".
   		              " LEFT OUTER JOIN ".
			              " ( ".
            	              " SELECT ".
				                " sub_ts.TradeID, ".
				                " sub_s.SystemID, ".
				                " sub_s.Name as SysName, ".
				                " sub_s.TimeFrame, ".
				                " sub_s.Description ".
				              " FROM ".
               		              " fa_trades_systems sub_ts ".
            			              " LEFT OUTER JOIN fa_systems sub_s ON (sub_ts.SystemID = sub_s.SystemID) ".
				              " WHERE sub_s.Active=1 AND isSignal=1 AND sub_s.Paused=0 ".
        	              " ) ts ".
		              " ON (ts.TradeID = t.TradeID) ".
		              //" LEFT JOIN ".
			              //"  us ".
		              //" ON (t.systemID = us.subscr_system) ".
              " WHERE ts.SystemID is not null ".
              " ORDER BY ts.SystemID, t.TradeID ";

            $this->_querys['select_trades_ea'] =
              " SELECT ".
                " CONCAT('" . $this->UserRecord->userid . "', '_', ts.SystemID, '_', t.TradeID) as value, ".
                " t.Pair as name, ".
                " ts.SystemID as `group`, ".
                " COALESCE( ".
  				              " ( ".
  				               " SELECT ut.TradeID is not null ".
                               " FROM fa_users_trades_ea ut ".
                               " WHERE ut.TradeID = t.TradeID AND ut.SystemID=ts.SystemID AND ut.UserID = ".$this->UserRecord->userid." AND ut.Active=1 ".
				              " ), ".
			              " 0) as flag, ".
				" ( ".
	  				" SELECT ROUND(ea.LotSize/1000) ".
	      			" FROM fa_users_trades_ea ea ".
	         		" WHERE ea.TradeID = t.TradeID AND ea.SystemID=ts.SystemID AND ea.UserID = ".$this->UserRecord->userid.
					" ) as lot, ".
				" (SELECT count(*) FROM fa_subscriptions WHERE user_id=".$this->UserRecord->userid." AND subscr_active=1)>0 as subscribed, ".
			     " (SELECT count(*) FROM fa_subscriptions sss WHERE sss.user_id=".$this->UserRecord->userid." AND sss.subscr_active=1 AND sss.subscr_system=ts.SystemID)>0 as subscr_system ".
              " FROM ".
  	              " fa_trades t ".
   		              " LEFT OUTER JOIN ".
			              " ( ".
            	              " SELECT ".
				                " sub_ts.TradeID, ".
				                " sub_s.SystemID, ".
				                " sub_s.Name as SysName, ".
				                " sub_s.TimeFrame, ".
				                " sub_s.Description ".
				              " FROM ".
               		              " fa_trades_systems sub_ts ".
            			              " LEFT OUTER JOIN fa_systems sub_s ON (sub_ts.SystemID = sub_s.SystemID) ".
				              " WHERE sub_s.Active=1 AND isAT=1 AND sub_s.Paused=0 ".
        	              " ) ts ".
		              " ON (ts.TradeID = t.TradeID) ".
              " WHERE ts.SystemID is not null ".
              " ORDER BY ts.SystemID, t.TradeID ";

            $this->_querys['select_lang'] = " SELECT  sys_name as value, name FROM fa_language ";
            $this->_querys['select_brokers'] = 'SELECT * FROM fa_brokers WHERE Active=1';
            $this->_querys['select_money'] = 'SELECT * FROM fa_money_management WHERE UserID=?';

            $this->_querys['check_money_record'] = 'SELECT count(*) as mm FROM fa_money_management WHERE UserID=?';
            $this->_querys['insert_money_record'] = 'INSERT INTO fa_money_management (UserID, AccountSize, BrokerID, BrokerCustom) VALUES (?, ?, ?, ?)';
            $this->_querys['update_money_record'] = 'UPDATE fa_money_management SET AccountSize=?, BrokerID=?, BrokerCustom=? WHERE UserID=?';

            $this->_querys['delete_trades'] = 'delete from fa_users_trades where userid=?';
            $this->_querys['insert_trades'] = 'insert into fa_users_trades (UserID, SystemID, TradeID) values (?, ?, ?)';

            $this->_querys['activate_trades_ea'] = "update fa_users_trades_ea set Active=1, LotSize=? where UserID=? and TradeID=? and SystemID=?";
            $this->_querys['deactivate_trades_ea'] = 'update fa_users_trades_ea set Active=0 where userid=?';

            $this->_querys['insert_trades_ea'] = ' INSERT INTO fa_users_trades_ea(UserID, SystemID, TradeID)   '.
                                            ' (SELECT ? as UserID, ts.SystemID, ts.TradeID ' .
                                            '  FROM fa_trades_systems ts)';
			$this->_querys['insert_trade_ea'] = ' INSERT INTO fa_users_trades_ea(UserID, SystemID, TradeID)   '.
                                            ' VALUES (?,?,?)';
											
            $this->_querys['check_trades_ea'] = 'SELECT count(*) as Eatrades FROM fa_users_trades_ea WHERE UserID=?';
			$this->_querys['check_trade_ea'] = 'SELECT count(*) as Eatrade FROM fa_users_trades_ea WHERE UserID=? AND SystemID=? AND TradeID=?';
        } //_sqls
    } //class UserProfile
    //---------------------------------------------------------------------------------------------------
    class objUserUnsubscribe extends objUserAction{
            public $code = false;
	    protected $_user = false;

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        protected function _Perform() {
            parent::_Perform();

            if( !$this->_Params->isEmpty() ) {
                $params = $this->_Params->getAssocArray();
                try {
                    $this->_user = $this->_DataBase->handler->GetRow($this->_querys['find_user'], array($this->code));
                    //-----------------------------------------------------------------------------------
                    if( $this->_user ) $this->_DataBase->handler->Execute($this->_querys['update_user'],  array($this->code));

                } catch(exception $e) {
                    if (true == $this->_DataBase->handler->debug ) {
                        adodb_pr($e);
                        $e = adodb_backtrace($e->trace);
                    }
                    print('Error: '.$e->sql.' '.$e->getMessage());
                    return false;
                }
            }
            return true;
	}//_Perform

    public function Render() {
            if( !$this->_Perform() ) return false;

            $result = 'User '.$this->_user['Name'] .'('.$this->_user['Login'].') was successful unsubscribed.';
            return $result;
    } //Render

    protected function _sqls() {
	    $this->_querys['find_user'] =
		" SELECT  u.Login,u.Name,u.Login ".
		" FROM fa_users u ".
		" WHERE md5(concat('unsubscribe',u.Login,'the knowledge is the power.'))=? ";

	    $this->_querys['update_user'] =
		" UPDATE fa_users SET MessageType=0 ".
		" WHERE md5(concat('unsubscribe',u.Login,'the knowledge is the power.'))=? ";

    } //_sqls


    } //class UserUnsubscribe


//-------------------------------------------------------------------------------------------------------

    class objUserTracking extends objUserAction{
            public $code = false;
	    protected $_user = false;
	    public $tracking_data = array();

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public  function __construct() {
        	$this->_DataBase = objDataBase::GetInstance();
            $this->_sqls();
        } //constructor


        public  function getTrackingInfo ($env_vars) {
        	if (!$_SERVER) return false;

            $this->tracking_data['ip'] = $_SERVER['REMOTE_ADDR'];
            $this->tracking_data['host'] = gethostbyaddr($_SERVER['REMOTE_ADDR']);
            $this->tracking_data['agent'] = $_SERVER['HTTP_USER_AGENT'];
            //$this->tracking_data['referer'] = $_SERVER['HTTP_REFERER'];

            //var_dump($this->tracking_data);
            return true;
        } //constructor


        public function insertTrackingInfo($user_id) {
        	$this->tracking_data['id'] = $user_id;

            try {
                $this->_DataBase->handler->Execute($this->_querys['insert_user_info'], $this->tracking_data);
            } catch(exception $e) {
                if (true == $this->_DataBase->handler->debug ) {
                    adodb_pr($e);
                    $e = adodb_backtrace($e->trace);
                }
                print('Error: '.$e->sql.' '.$e->getMessage());
                return false;
            }

            return true;
	}


    protected function _sqls() {
	    $this->_querys['insert_user_info'] =
		" INSERT INTO fa_users_tracking ".
		" (UserIP, UserHost, UserAgent, UserID) ".
		" VALUES(?,?,?,?) ";

	    $this->_querys['update_user'] =
		" UPDATE fa_users SET MessageType=0 ".
		" WHERE md5(concat('unsubscribe',u.Login,'the knowledge is the power.'))=? ";

    } //_sqls


    } //class UserUnsubscribe


//-------------------------------------------------------------------------------------------------------
class objUserSubscription {
	public $code = false;
	protected $_user = false;
	public $userData = array();
	public $activateSubscription = 0;
	public $subscriptionStart = 0;
	public $subscriptionEnd = false;
	public $subscrStartTime;
	public $paymentCompleted = "Completed";


    public function __construct() {
    	$this->_DataBase = objDataBase::GetInstance();
    	$this->_DataBase->debug = true;
        $this->_sqls();
    } //constructor


    protected function _deleteUserTrades ($userID) {
        $this->_DataBase->handler->Execute($this->_querys['delete_trades'], array($userID));
        return true;
    }

    protected function _setSubscriptionTrades ($userID, $subscrID=false) {
        $this->_DataBase->handler->Execute($this->_querys['set_subscr_trades'], array($userID, $userID));
        return true;
    }
	
	protected function _setSubscriptionSystemTotals ($userID, $systemID) {
        $this->_DataBase->handler->Execute($this->_querys['update_subscriptions_totals1'], array($userID, $systemID));
		$this->_DataBase->handler->Execute($this->_querys['update_subscriptions_totals2'], array($userID, $systemID));
        return true;
    }

	//check if DB record for user exists
	public function checkSubscrRecordExists ($userID, $invoice) {
        $rcd = $this->_DataBase->handler->GetRow($this->_querys['check_subscription'], array($userID, $invoice));

        if ($rcd['subscriptions']>0) {
        	return true;
        } else return false;
    }

    public function getUserInvoiceData ($invoice, $payment_status) {
		$subscrID = explode("_",$invoice);

		$systemSets = explode("-", $subscrID[3]);
		foreach ($systemSets as $systemSet){
			$items = explode("%", $systemSet);
			$this->userData['subscrSystems'][] = array(
				'system' => $items[0],
				'period' => $items[1],
				'end' => (time()+86400*$items[1]));
		}

		$this->userData['userID'] = $subscrID[0];
		$this->userData['subscrType'] = $subscrID[2];
		$this->userData['subscr_id'] = $subscrID[4];
		//$this->userData['subscrSystems'] = explode("-",$subscrID[4]);
		$this->userData['subscrTime'] = time();
		$this->userData['subscrID'] = $invoice;
		$this->userData['payment'] = $payment_status;
		$this->userData['invoice'] = $invoice;

        return $this->userData;
    }


    public function terminateUserSubscription ($userID, $subscrID, $subscrSystem) {
    	$this->_DataBase->handler->Execute($this->_querys['terminate_subscription'], array($userID, $subscrID, $subscrSystem));
        $this->_DataBase->handler->Execute($this->_querys['delete_trades'], array($userID));
        return true;
    }


    public function processSubscription () {
        if ( !$this->checkSubscrRecordExists ($this->userData['userID'], $this->userData['subscrID']) ) {
	       	$this->_querys['create_subscription'] = "INSERT INTO `fa_subscriptions` (user_id, subscr_system, subscr_id, subscr_time, subscr_start, subscr_end, subscr_status, subscr_type, subscr_active, subscr_period) VALUES";
			$systems = $this->userData['subscrSystems'];
			$systemCount = count($this->userData['subscrSystems']);
			$counter = 1; // counter for multiple Insert query generation
	     	foreach ($systems as $system ){
	        	$this->_querys['create_subscription'] .= "(".
	        	$this->userData['userID'].", ".
	           	$system['system'].", ".
	           	"'".$this->userData['subscrID']."', ".
	           	$this->userData['subscrTime'].", ".
	           	$this->subscriptionStart.", ".
				( ($this->subscriptionEnd==1)? $system['period'] : 0 ).", ".
	   			"'".$this->userData['payment']."', ".
				"'".$this->userData['subscrType']."', ".
				$this->activateSubscription.", ".
	  			$system['period'];

	  			if ($counter < $systemCount) $this->_querys['create_subscription'] .= "), ";
	  			else $this->_querys['create_subscription'] .= ")";
	  			$counter++;
	     	}
	      	$recordSet = $this->_DataBase->handler->Execute($this->_querys['create_subscription']);
	      	echo "<br>INSERT<br>";
       	} else {
       		$recordSet = $this->_DataBase->handler->Execute($this->_querys['update_subscription'], array(
	   			$this->userData['payment'],
	   			$this->userData['subscrTime'],
	           	$this->subscriptionStart,
				$this->activateSubscription,
				$this->userData['userID'],
				$this->userData['subscrID']
       		));
       		echo "<br>UPDATE<br>";
       	}


       	// set proper trades only after subscription payment
      	if ($this->userData['payment']==$this->paymentCompleted) {
       		$this->_deleteUserTrades($this->userData['userID']);
      		$this->_setSubscriptionTrades ($this->userData['userID']);
			// update subscription totals (date, days left) for every system
			foreach ($this->userData['subscrSystems'] as $system ){
				$this->_setSubscriptionSystemTotals ($this->userData['userID'], $system['system']);
			}
		}

  		return true; 
	}



	protected function _sqls() {
		$this->_querys['set_subscr_trades'] = "INSERT INTO fa_users_trades(UserID, SystemID, TradeID) ".
	 		" (SELECT DISTINCT ? as UserID, ts.SystemID, ts.TradeID ".
	   		" FROM fa_trades_systems ts RIGHT JOIN fa_subscriptions st ON st.subscr_system=ts.SystemID ".
	   		" WHERE st.user_id=? AND st.subscr_active=1)";

		$this->_querys['check_subscription'] = "SELECT count(*) as subscriptions FROM fa_subscriptions ".
		" WHERE user_id=? AND subscr_id=?";
		$this->_querys['create_subscription'] = "INSERT INTO `fa_subscriptions` (user_id,subscr_system,subscr_id,subscr_time,subscr_start,subscr_end,subscr_status,subscr_type,subscr_active,subscr_period) VALUES(?,?,?,?,?,?,?,?,?,?)";
		$this->_querys['update_subscription'] = "UPDATE fa_subscriptions ".
		" SET subscr_status=?, subscr_time=?, subscr_start=?, subscr_active=? ". 
		" WHERE user_id=? AND subscr_id=?";
		$this->_querys['update_subscriptions_totals1'] = " SET @totalDaysLeft = ".
			" ( SELECT ROUND( SUM( ((s2.subscr_time+s2.subscr_period*86400)-UNIX_TIMESTAMP())/86400 ) ) ".
			" FROM fa_subscriptions s2 ".
			" WHERE s2.user_id=? AND s2.subscr_system=? AND s2.subscr_active='1' ); ";    
		$this->_querys['update_subscriptions_totals2'] = "UPDATE fa_subscriptions s ".
		" SET s.subscr_system_date=UNIX_TIMESTAMP(), s.subscr_system_period=@totalDaysLeft ".
		" WHERE s.user_id=? AND s.subscr_system=? AND s.subscr_active=1";  
		
		$this->_querys['terminate_subscription'] = "UPDATE fa_subscriptions ".
		" SET subscr_end=UNIX_TIMESTAMP(), subscr_active=0 ".
		" WHERE user_id=? AND subscr_id=? AND subscr_system=?"; 

		$this->_querys['delete_trades'] = 'DELETE FROM fa_users_trades WHERE UserID=?';
	 	$this->_querys['insert_trades'] = 'insert into fa_users_trades (UserID, SystemID, TradeID) values (?, ?, ?)';  


	} //_sqls


} //class UserUnsubscribe



?>
